﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DeskRedis.Util
{
    public static class JsonUtil
    {
        public static T GetConfigObject<T>(string path)
        {
            StreamReader sr = new StreamReader(path, Encoding.Default);
            string json = sr.ReadToEnd();
            sr.Close();

            T connections = JsonConvert.DeserializeObject<T>(json);
            return connections;
        }

        public static void SetConfigObject<T>(string path, T obj)
        {
            string connections = JsonConvert.SerializeObject(obj, Formatting.Indented);

            StreamWriter sw = new StreamWriter(path, false, Encoding.Default);
            sw.Write(connections);
            sw.Flush();
            sw.Close();
        }

        public static string FormateJsonString(string str)
        {
            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("[01]");
            if (r.IsMatch(str))
            {
                return str;
            }
            else
            {
                //格式化json字符串
                JsonSerializer serializer = new JsonSerializer();
                TextReader tr = new StringReader(str);
                JsonTextReader jtr = new JsonTextReader(tr);
                object obj = serializer.Deserialize(jtr);
                if (obj != null)
                {
                    StringWriter textWriter = new StringWriter();
                    JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
                    {
                        Formatting = Formatting.Indented,
                        Indentation = 4,
                        IndentChar = ' '
                    };
                    serializer.Serialize(jsonWriter, obj);
                    return textWriter.ToString();
                }
                else
                {
                    return str;
                }
            }
        }
    }
}
